<template>
  <div class="user-container">
    <div class="user-content">
      <!-- 左侧用户信息和菜单 -->
      <div class="user-sidebar">
        <div class="user-info">
          <div class="avatar">
            <img :src="userProfile.avatarUrl || '../assets/homelogo.png'" alt="用户头像" />
            <div class="vip-badge">会员</div>
            <div class="avatar-edit" @click="showAvatarDialog">
              <i class="el-icon-edit"></i>
            </div>
          </div>
          <div class="user-detail">
            <div class="username">{{ userProfile.nickname || userProfile.username }}</div>
            <div class="phone">{{ userProfile.phone || '未设置' }}</div>
            <div class="user-actions">
              <el-button type="text" @click="showProfileDialog">编辑资料</el-button>
              <el-button type="text" @click="showPasswordDialog">修改密码</el-button>
            </div>
          </div>
        </div>
        
        <div class="user-menu">
          <div class="menu-title active">收货地址管理</div>
        </div>
      </div>
      
      <!-- 右侧内容区域 -->
      <div class="user-main">
        <div class="section address-section">
          <div class="section-header">
            <h2>收货地址管理</h2>
            <el-button type="primary" size="small" @click="handleAddNewAddress">新增地址</el-button>
          </div>
          
          <div class="address-list">
            <el-empty v-if="addresses.length === 0" description="暂无收货地址"></el-empty>
            <div class="address-item" v-for="address in addresses" :key="address.id">
              <div class="address-content">
                <div class="contact-info">
                  <span class="contact-name">{{ address.contactName }}</span>
                  <span class="contact-phone">{{ address.phone }}</span>
                  <el-tag v-if="address.isDefault" size="small" type="success">默认</el-tag>
                </div>
                <div class="address-text">{{ formatAddress(address) }}</div>
              </div>
              <div class="address-actions">
                <el-button type="text" @click="setAsDefault(address)" v-if="!address.isDefault">设为默认</el-button>
                <el-button type="text" @click="handleEditAddress(address)">编辑</el-button>
                <el-button type="text" @click="confirmDeleteAddress(address)">删除</el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 添加/编辑地址对话框 -->
    <el-dialog
      v-model="addressDialogVisible"
      :title="isEditingAddress ? '编辑地址' : '添加收货地址'"
      width="500px"
    >
      <el-form 
        ref="addressFormRef"
        :model="addressForm"
        :rules="addressRules"
        label-width="0px"
      >
        <el-form-item prop="contactName">
          <el-input 
            v-model="addressForm.contactName" 
            placeholder="收货人姓名" 
            size="large"
          />
        </el-form-item>
        
        <el-form-item prop="phone">
          <el-input 
            v-model="addressForm.phone" 
            placeholder="收货人手机号" 
            size="large"
          />
        </el-form-item>
        
        <el-form-item prop="region">
          <el-cascader
            v-model="addressForm.region"
            :options="regionOptions"
            placeholder="福建省 厦门市 集美区"
            size="large"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item prop="street">
          <div class="address-input-container">
            <el-input
              v-model="addressForm.street"
              placeholder="如街道、门牌号、小区、乡镇、村等"
              size="large"
              class="address-input"
            />
            <el-button 
              type="danger" 
              size="large" 
              class="location-btn"
              @click="handleGetLocation"
              :loading="isLocating"
            >
              定位
            </el-button>
          </div>
        </el-form-item>
        
        <el-form-item>
          <div class="default-address-container">
            <el-checkbox 
              v-model="addressForm.isDefault" 
              size="large"
              class="default-checkbox"
              @change="handleDefaultAddressChange"
            >
              设为默认地址
            </el-checkbox>
            <div v-if="addressForm.isDefault" class="default-tip">
              <i class="el-icon-info"></i>
              <span>设为默认后，其他默认地址将自动取消</span>
            </div>
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button 
            type="danger" 
            size="large" 
            @click="handleSaveAddress"
            class="save-btn"
          >
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 头像更新对话框 -->
    <el-dialog v-model="avatarDialogVisible" title="更新头像" width="400px">
      <el-form>
        <el-form-item label="头像图片">
          <div class="file-upload-group">
            <input 
              ref="avatarFileInput" 
              type="file" 
              accept="image/*" 
              @change="handleFileUpload" 
              style="display: none;"
            >
            <div class="upload-area" @click="triggerAvatarUpload">
              <div v-if="avatarForm.avatarUrl" class="preview-container">
                <img :src="avatarForm.avatarUrl" alt="头像预览" class="avatar-preview">
                <div class="upload-overlay">
                  <span>点击更换图片</span>
                </div>
              </div>
              <div v-else class="upload-placeholder">
                <span>点击上传头像图片</span>
              </div>
            </div>
            <button 
              v-if="avatarForm.avatarUrl" 
              type="button" 
              @click="clearAvatar" 
              class="clear-btn"
            >
              清除图片
            </button>
          </div>
        </el-form-item>
        <el-form-item label="或直接输入URL">
          <el-input v-model="avatarForm.avatarUrl" placeholder="请输入头像图片URL" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="avatarDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleUpdateAvatar">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 个人资料更新对话框 -->
    <el-dialog v-model="profileDialogVisible" title="编辑个人资料" width="500px">
      <el-form 
        ref="profileFormRef"
        :model="profileForm"
        :rules="profileRules"
        label-width="100px"
      >
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="profileForm.nickname" placeholder="请输入昵称" />
        </el-form-item>
        
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="profileForm.phone" placeholder="请输入手机号码" />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="profileForm.email" placeholder="请输入邮箱" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="profileDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleUpdateProfile">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 密码修改对话框 -->
    <el-dialog v-model="passwordDialogVisible" title="修改密码" width="500px">
      <el-form 
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="当前密码" prop="oldPassword">
          <el-input 
            v-model="passwordForm.oldPassword" 
            type="password"
            placeholder="请输入当前密码（邮箱登录用户默认为qq号）" 
            show-password
          />
        </el-form-item>
        
        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="passwordForm.newPassword" 
            type="password"
            placeholder="请输入新密码" 
            show-password
          />
        </el-form-item>
        
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input 
            v-model="passwordForm.confirmPassword" 
            type="password"
            placeholder="请再次输入新密码" 
            show-password
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleUpdatePassword">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserProfile } from '../composables/useUserProfile'
import { useAddress } from '../composables/useAddress'
import { useGeolocation } from '../composables/useGeolocation'

// 对话框状态
const addressDialogVisible = ref(false)
const avatarDialogVisible = ref(false)
const profileDialogVisible = ref(false)
const passwordDialogVisible = ref(false)

// 表单引用
const addressFormRef = ref<any>(null)
const profileFormRef = ref<any>(null)
const passwordFormRef = ref<any>(null)
const avatarFileInput = ref<HTMLInputElement>()

// 使用组合函数
const {
  userProfile,
  avatarForm,
  profileForm,
  passwordForm,
  profileRules,
  passwordRules,
  fetchUserInfo,
  updateAvatar,
  updateProfile,
  updatePassword,
  handleAvatarUpload
} = useUserProfile()

const {
  addresses,
  addressesLoading,
  isEditingAddress,
  addressForm,
  addressRules,
  regionOptions,
  formatAddress,
  fetchAddresses,
  addNewAddress,
  editAddress,
  saveAddress,
  setAsDefault,
  confirmDeleteAddress,
  fillAddressInfo
} = useAddress()

const {
  isLocating,
  getCurrentLocation
} = useGeolocation()

// 地址相关处理函数
const handleAddNewAddress = () => {
  addNewAddress()
  addressDialogVisible.value = true
}

const handleEditAddress = (address: any) => {
  editAddress(address)
  addressDialogVisible.value = true
}

const handleSaveAddress = async () => {
  if (!addressFormRef.value) return
  
  await addressFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    
    const success = await saveAddress()
    if (success) {
      addressDialogVisible.value = false
    }
  })
}

const handleGetLocation = async () => {
  const locationData = await getCurrentLocation()
  if (locationData) {
    fillAddressInfo(locationData)
  }
}

const handleDefaultAddressChange = (value: boolean) => {
  if (value) {
    ElMessage.info('设为默认后，您的其他默认地址将自动取消')
  }
}

// 用户资料相关处理函数
const showAvatarDialog = () => {
  avatarForm.avatarUrl = userProfile.value.avatarUrl || ''
  avatarDialogVisible.value = true
}

const showProfileDialog = () => {
  profileForm.nickname = userProfile.value.nickname || ''
  profileForm.phone = userProfile.value.phone || ''
  profileForm.email = userProfile.value.email || ''
  profileDialogVisible.value = true
}

const showPasswordDialog = () => {
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  passwordDialogVisible.value = true
}

const triggerAvatarUpload = () => {
  avatarFileInput.value?.click()
}

const handleFileUpload = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  
  if (file) {
    await handleAvatarUpload(file)
  }
  
  if (target) target.value = ''
}

const clearAvatar = () => {
  avatarForm.avatarUrl = ''
}

const handleUpdateAvatar = async () => {
  const success = await updateAvatar()
  if (success) {
    avatarDialogVisible.value = false
  }
}

const handleUpdateProfile = async () => {
  if (!profileFormRef.value) return
  
  await profileFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    
    const success = await updateProfile()
    if (success) {
      profileDialogVisible.value = false
    }
  })
}

const handleUpdatePassword = async () => {
  if (!passwordFormRef.value) return
  
  await passwordFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    
    const success = await updatePassword()
    if (success) {
      passwordDialogVisible.value = false
    }
  })
}

// 初始化数据
const initializeData = async () => {
  await Promise.all([
    fetchUserInfo(),
    fetchAddresses()
  ])
}

onMounted(() => {
  initializeData()
})
</script>

<style scoped>
/* 文件上传相关样式 */
.file-upload-group {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 15px;
}

.upload-area {
  width: 150px;
  height: 150px;
  border: 2px dashed #dcdfe6;
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  margin-bottom: 10px;
  overflow: hidden;
  position: relative;
}

.upload-area:hover {
  border-color: #409eff;
}

.upload-placeholder {
  color: #909399;
  font-size: 14px;
  text-align: center;
  padding: 10px;
}

.preview-container {
  width: 100%;
  height: 100%;
  position: relative;
}

.avatar-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.preview-container:hover .upload-overlay {
  opacity: 1;
}

.clear-btn {
  margin-top: 5px;
  padding: 5px 10px;
  background-color: #f56c6c;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.clear-btn:hover {
  background-color: #e74c3c;
}

.user-container {
  width: 100%;
  min-height: 100vh;
  margin: 0;
  padding: 0;
  font-family: Arial, sans-serif;
  background-color: #fff;
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
}

.user-content {
  display: flex;
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

/* 左侧边栏 */
.user-sidebar {
  width: 250px;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-right: 20px;
}

.user-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
  margin-bottom: 20px;
}

.avatar {
  position: relative;
  width: 80px;
  height: 80px;
  border-radius: 50%;
  overflow: hidden;
  margin-bottom: 15px;
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.vip-badge {
  position: absolute;
  bottom: 0;
  right: 0;
  background-color: #f56c6c;
  color: white;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 10px;
}

.avatar-edit {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s;
  cursor: pointer;
}

.avatar-edit i {
  color: white;
  font-size: 20px;
}

.avatar:hover .avatar-edit {
  opacity: 1;
}

.user-detail {
  text-align: center;
}

.username {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 5px;
}

.phone {
  color: #666;
  font-size: 14px;
  margin-bottom: 10px;
}

.user-actions {
  display: flex;
  justify-content: center;
  gap: 10px;
}

.user-menu {
  display: flex;
  flex-direction: column;
}

.menu-title {
  padding: 12px 0;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  border-bottom: 1px solid #eee;
}

.menu-title.active {
  color: #409eff;
}

/* 右侧内容区域 */
.user-main {
  flex: 1;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
  width: calc(100% - 270px);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.section-header h2 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

/* 地址列表 */
.address-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.address-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 4px;
}

.address-content {
  flex: 1;
}

.contact-info {
  margin-bottom: 8px;
}

.contact-name {
  font-weight: bold;
  margin-right: 10px;
}

.contact-phone {
  color: #666;
  margin-right: 10px;
}

.address-text {
  color: #333;
}

.address-actions {
  display: flex;
  gap: 10px;
}

/* 对话框样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 地址输入容器样式 */
.address-input-container {
  display: flex;
  gap: 10px;
  align-items: center;
}

.address-input {
  flex: 1;
}

.location-btn {
  min-width: 80px;
  background-color: #ff4757 !important;
  border-color: #ff4757 !important;
}

.location-btn:hover {
  background-color: #ff3742 !important;
  border-color: #ff3742 !important;
}

/* 保存按钮样式 */
.save-btn {
  width: 100%;
  background-color: #ff4757 !important;
  border-color: #ff4757 !important;
  font-size: 16px;
  padding: 12px 0;
}

.save-btn:hover {
  background-color: #ff3742 !important;
  border-color: #ff3742 !important;
}

/* 默认地址选择框样式 */
.default-address-container {
  display: flex;
  flex-direction: column;
  padding: 8px 0;
}

.default-checkbox {
  font-size: 16px;
  margin-bottom: 8px;
}

.default-checkbox .el-checkbox__label {
  color: #333;
  font-weight: 500;
}

.default-tip {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.default-tip i {
  margin-right: 5px;
  color: #409eff;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .user-content {
    flex-direction: column;
  }
  
  .user-sidebar {
    width: 100%;
    margin-bottom: 20px;
    margin-right: 0;
  }
  
  .user-main {
    width: 100%;
  }
}
</style>